<?php

namespace app\command;

use app\model\User;
use schedule\console\Command;
use think\console\Input;
use think\console\Output;

class UserInviteRankUpgradeCommand extends Command
{
	protected function configure()
	{
		$this->setName('userInviteRank')->setDescription('用户安置位重新分配脚本');
	}

	protected function execute(Input $input, Output $output)
	{
		// 分页查询所有用户
		$pageSize  = 10;
		$count     = intval(User::count());
		$totalPage = ceil($count / $pageSize);

		for ($page = 1; $page <= $totalPage; $page++) {

			$offset = ($page - 1) * $pageSize;
			$limit  = $pageSize;

			// 查询用户列表
			$userList = User::where('id', '>', 1)->limit($offset, $limit)->select()->toArray();

			foreach ($userList as $item) {
				$rank_prev = [
					'rank'       => '|' . $item['id'] . '|',
					'rank_level' => 0,
					'id'         => 0,
				];

				$parentUserInfo = User::where('id', $item['parent_user_id'])->where('status', 1)->find();

				if (!empty($parentUserInfo)) {
					if ($parentUserInfo['rank_next_count'] < rankNextMax()) {
						$rank_prev = $parentUserInfo;
					} else {
						$rank        = '|' . $parentUserInfo['id'] . '|';
						$rankPrevRes = User::where([
							['rank', 'like', '%' . $rank . '%'],
							['rank_next_count', '<', rankNextMax()],
						])->order(['rank_level', 'rank_next_count', 'id'])->find();
						if ($rankPrevRes) {
							$rank_prev = $rankPrevRes;
						}
					}
				}

				$update = [
					'rank'       => $rank_prev['rank'] . $item['id'] . '|',
					'rank_level' => $rank_prev['rank_level'] + 1,
					'rank_pid'   => $rank_prev['id'],
				];

				User::transaction(function () use ($item, $update, $rank_prev) {
					$res1 = User::where('id', $item['id'])->update($update);

					$res2 = $rank_prev->save(['rank_next_count' => $rank_prev['rank_next_count'] + 1]);

					if (!$res1 || !$res2) {
						echo "更新失败，数据：\n";
						print_r($update);
					}
				});
			}

			echo "\n";
			echo "当前页码：{$page}\n";
			echo "总共页码：{$totalPage}\n";
			$execCount = $page * $pageSize;
			echo "已执行{$execCount}条数据\n";
		}
	}
}
